package org.korosoft.rusalad.syncnrun.cli;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.korosoft.rusalad.syncnrun.Client;
import org.korosoft.rusalad.syncnrun.command.AbstractSyncCmd;
import org.korosoft.rusalad.syncnrun.command.SyncLocalDirCmd;

/**
 * Upload files to remote server command
 *
 * @author Dmitry Korotkov
 * @since 1.0
 */
public class CliSend extends CliClientCommand {
    private static final Log log = LogFactory.getLog(CliSend.class);

    public CliSend() {
        super("send", "Sends file or directory to remove syncnrun server");
        options.addOption(OptionBuilder.withLongOpt("source").withDescription("Local file or directory").hasArg().isRequired().create("s"));
        options.addOption(OptionBuilder.withLongOpt("target").withDescription("Remote target directory").hasArg().isRequired().create("t"));
        addCommonLoggingOpts();
    }

    @Override
    protected int doExecute(Client client, CommandLine commandLine) throws Exception {
        String source = commandLine.getOptionValue("source");
        String target = commandLine.getOptionValue("target");

        AbstractSyncCmd.LocalFilesInfo info = AbstractSyncCmd.prepareLocalFilesInfo(source);
        long startTime = System.currentTimeMillis();
        SyncLocalDirCmd.SyncLocalDirAnswer syncLocalDirAnswer = client.execCommandSynchronously(new SyncLocalDirCmd(target, info));
        long duration = System.currentTimeMillis() - startTime;
        log.info(String.format("Transferred %d bytes in %d second at rate %f MB/s", syncLocalDirAnswer.bytesSent, duration / 1000, syncLocalDirAnswer.bytesSent * 1.0 / (duration * 1000.0)));
        return 0;
    }


}
